#include "ServerListenController.h"

ServerListenController::ServerListenController(Model *m, View *v, NetworkPat* net): Controller(m, v)
{
  _model = (ServerListenModel*)m;
  _view = (ServerListenView*)v;
  _net = net;
  newGameState = GameState::ServerListen;
  mShouldReset = true;
}

ServerListenController::~ServerListenController(void)
{
}

void ServerListenController::HandleMessages(std::list<Message*> *l)
{
  if(l == NULL)
    return;
  //get messages from the network
  if(mShouldReset)
  {
    _net->Reset();
    _model->mListenAddr = _net->GetAddr();
    _model->mListenPort = _net->GetPort();
    mShouldReset = false;
  }
  std::list<Message*>* l2 = _net->Recv();

  newGameState = GameState::ServerListen;
  while(!l->empty())
  {
    Message* temp = l->front();
    l->pop_front();
    if(temp->GetMessageType() == MessageType::USER_INPUT)
    {
      switch(temp->GetMessageContent())
      {
        case GameAction::MOVE_UP:
          _model->IncrementMenuItemUp();
          break;
        case GameAction::MOVE_DOWN:
          _model->IncrementMenuItemDown();
          break;
        case GameAction::SELECT:
          int selection = _model->GetSelectedMenuItem();
          if(selection == 0)
          {
            for(int i = 0; i < _net->GetCount(); ++i)
            {
              Message* msg = new Message(MessageType::SYSTEM, NetMessage::ID_ASSIGNMENT);
              msg->SetMessageId(i + 1);
              _net->SendToOne(msg, i);
            }
            Message* msg2 = new Message(MessageType::SYSTEM, NetMessage::RANDOM_SEED);
            msg2->SetMessageId(RandomNumberGenerator::GetRandomNumber(1, 10000));
            _net->Send(msg2);
            newGameState = GameState::ServerPlay;
            mShouldReset = true;
          }
          if(selection == 1)
          {
            Message* msg = new Message(MessageType::SYSTEM, NetMessage::END);
            _net->Send(msg);
            mShouldReset = true;
            newGameState = GameState::MainMenu;
          }
          break;
      }
    }
    delete temp;
  }
  while(!l2->empty())
  {
    Message* temp = l2->front();
    l2->pop_front();
    if(temp->GetMessageType() == MessageType::SYSTEM)
    {
      switch(temp->GetMessageContent())
      {
        case NetMessage::JOIN:
          if(_net->GetCount() < MAX_PLAYERS)
          {
            _net->SetCount(_net->GetAddrCount());
            Message* msg = new Message(MessageType::SYSTEM, NetMessage::PLAYER_COUNT_UPDATE);
            msg->SetMessageId(_net->GetCount());
            _net->Send(msg);
          }
          break;
      }
    }
    delete temp;
  }
}

GameState ServerListenController::Update(void)
{
  _view->DrawScreen();
  return newGameState;
}

void ServerListenController::PassMessage(Message* msg)
{
}

void ServerListenController::ProcessMessages(void)
{
}
